package com.cbtx.module.base.http;


import android.content.Context;
import android.content.res.AssetManager;

import com.google.gson.Gson;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;


public class GsonUtil {
    public static Gson gson;

    /**
     * json解析
     *
     * @param json 字符串格式的json
     * @param clz  对象名
     * @return
     */
    public static <T> T jsonToBean(String json, Class<T> clz) {
        Gson mGson = new Gson();
        return mGson.fromJson(json, clz);
    }

    /**
     * json解析
     *
     * @param obj  对象名
     * @return
     */
    public static <T> String beanToJson(T obj) {
        Gson mGson = new Gson();
        return mGson.toJson(obj);
    }

    /**
     * 将map数据解析出来，并拼接成json字符串
     *
     * @param map
     * @return
     */
    @SuppressWarnings({"rawtypes", "unchecked"})
    public static String setJosn(Map map) throws Exception {
        StringBuffer temp = new StringBuffer();
        if (!map.isEmpty()) {
            temp.append("{");
            // 遍历map
            Set set = map.entrySet();
            Iterator i = set.iterator();
            while (i.hasNext()) {
                Map.Entry entry = (Map.Entry) i.next();
                String key = (String) entry.getKey();
                Object value = entry.getValue();
                temp.append("\"" + key + "\":");
                if (value instanceof Map<?, ?>) {
                    temp.append(setJosn((Map<String, Object>) value) + ",");
                } else if (value instanceof List<?>) {
                    temp.append(setList((List<Map<String, Object>>) value)
                            + ",");
                } else {
                    temp.append("\"" + value + "\",");
                }
            }
            if (temp.length() > 1) {
                temp = new StringBuffer(temp.substring(0, temp.length() - 1));
            }
            temp.append("}");
        }
        return temp.toString();
    }

    /**
     * 将单个list转成json字符串
     *
     * @param list
     * @return
     * @throws Exception
     */
    public static String setList(List<Map<String, Object>> list)
            throws Exception {
        String jsonL = "";
        StringBuffer temp = new StringBuffer();
        temp.append("[");
        for (int i = 0; i < list.size(); i++) {
            Map<String, Object> m = list.get(i);
            if (i == list.size() - 1) {
                temp.append(setJosn(m));
            } else {
                temp.append(setJosn(m) + ",");
            }
        }
        if (temp.length() > 1) {
            temp = new StringBuffer(temp.substring(0, temp.length()));
        }
        temp.append("]");
        jsonL = temp.toString();
        return jsonL;
    }

    /**
     * 将json格式的字符串解析成Map对象 <li>
     */
    @SuppressWarnings("rawtypes")
    public static HashMap<String, Object> toHashMap(String object) {
        HashMap<String, Object> data = new HashMap<String, Object>();
        // 将json字符串转换成jsonObject
        JSONObject jsonObject;
        try {
            jsonObject = new JSONObject(object);
            Iterator it = jsonObject.keys();
            // 遍历jsonObject数据，添加到Map对象
            while (it.hasNext()) {
                String key = String.valueOf(it.next());
                Object value = jsonObject.get(key);
                data.put(key, value);
            }
            return data;
        } catch (JSONException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return null;
    }

    public static Gson getInstance() {
        if (gson == null) {
            synchronized (Gson.class) {
                if (gson == null) {
                    gson = new Gson();
                }
            }
        }
        return gson;
    }


    /**
     * 读取json
     *
     * @param context
     * @param fileName
     * @return
     */
    public String getJson(Context context, String fileName) {

        StringBuilder stringBuilder = new StringBuilder();
        try {
            AssetManager assetManager = context.getAssets();
            BufferedReader bf = new BufferedReader(new InputStreamReader(
                    assetManager.open(fileName)));
            String line;
            while ((line = bf.readLine()) != null) {
                stringBuilder.append(line);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return stringBuilder.toString();
    }
}
